package com.test.demo.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.test.demo.entity.Account;
import com.test.demo.utils.JwtUtils;
import com.test.demo.utils.Result;
import com.test.demo.utils.Utils;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * <p>
 * 用户账号密码 前端控制器
 * </p>
 *
 * @author
 * @since 2023-01-13
 */
@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {

    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 400, message = "请求参数没填好"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    })

//    登录
    @ApiOperation(value = "用户登录", notes="用户登录")
    @GetMapping("/login")
    public Result<?> login(@RequestParam("username") String username, @RequestParam("password") String password) {

//        md5(password+salt) = 数据库存的password值
        //通过用户名查询用户
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getUsername, username)
                .last("limit 1");
        Account userInfo = accountService.getOne(wrapper);
        HashMap<Object, Object> returnInfo = new HashMap<>();
        if (userInfo != null) {
            if (userInfo.getPassword() != null) {
//                （解密）判断解码的密码是否等于数据库的
                if (userInfo.getPassword().equals(SecureUtil.md5(password + userInfo.getSalt()))) {
                    String token = JwtUtils.generateToken(userInfo);
                    HashMap<Object, Object> map = new HashMap<>();
                    map.put("id", userInfo.getId());
                    map.put("username", userInfo.getUsername());
                    map.put("token", token);
                    returnInfo.put("userInfo", map);
                    returnInfo.put("menuList", "");
                    return Result.success(map);
                }
            }
        }
        return Result.error("请检查用户名密码是否正确");
    }

    //    注册用户
    @ApiOperation(value = "用户注册", notes="用户注册")
    @GetMapping("/add")
    public Result<?> add(Account account){
        String password = account.getPassword();
        String salt = Utils.salt();
//        加密
        String resultPassword = SecureUtil.md5(password + salt);
//        赋值给salt字段
        account.setSalt(salt);
        account.setPassword(resultPassword);
        accountService.save(account);
        return Result.success();
    }
}
